<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>拖拽</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
    <style>
        * {
            user-select: none;
        }

        .box {
            position: absolute;
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>
<body>
<div id="root">
    <button @click="addBox">点击</button>
    <input type="number" placeholder="宽" class="width1">
    <input type="number" placeholder="高" class="height1">
    <input type="color" placeholder="颜色" class="color1">
    <div id="box"></div>

</div>
<script>
    let vm = new Vue({
        el: "#root",
        data() {
            return {}
        },
        methods: {
            addBox() {
                const box = document.getElementById('box')
                this.newBox(box)
            },
            newBox(ele) {
                const newBox = document.createElement('div');
                const width1 = document.getElementsByClassName('width1')[0].value
                const height1 = document.getElementsByClassName('height1')[0].value
                const color1 = document.getElementsByClassName('color1')[0].value

                newBox.style.width = width1 + 'px'
                newBox.style.height = height1 + 'px'
                newBox.style.backgroundColor = color1
                newBox.classList.add('box');
                ele.appendChild(newBox)
            },

            move() {
            },

            // 移动盒子
            moveBox(e) {
                if (e.target.tagName !== 'DIV') return;
                const l = e.offsetX
                const t = e.offsetY
                const isBox = e.target
                console.log(e.target.tagName)
                this.move = function (e) {
                    let x = e.clientX
                    let y = e.clientY
                    isBox.style.top = y - t + 'px'
                    isBox.style.left = x - l + 'px'
                }
                document.addEventListener('mousemove', this.move)
            },

        },
        mounted() {
            const that = this;
            // 给 newBox 添加拖拽事件 ———— 通过给 #box 添加事件委托
            const box = document.getElementById('box')
            box.addEventListener('mousedown', that.moveBox)
            document.addEventListener('mouseup', function () {
                document.removeEventListener('mousemove', that.move)
            })

        }
    })
</script>

</body>
</html>